也有英文版文章
Also this tutorial has been written in English
Check out my Medium
✨更多請看Rust檔案 - 所有權
注意兩個範例,第二個有註解,展示兩者差別。
❌ 這個範例會出現錯誤提示
// ❌❌❌
struct GroceryItem {
quantity: i32,
id: i32,
}
fn display_quantity(item: GroceryItem) {
println!("quantity: {:?}", item.quantity);
}
fn display_id(item: GroceryItem) {
println!("id: {:?}", item.id);
}
fn main() {
let my_item = GroceryItem {
quantity: 3,
id: 99,
};
display_quantity(my_item);
display_id(my_item);
}
✔️ 這個可以運作
// ✔️✔️✔️
struct GroceryItem {
quantity: i32,
id: i32,
}
fn display_quantity(item: &GroceryItem) { // Add &
println!("quantity: {:?}", item.quantity);
}
fn display_id(item: &GroceryItem) { // Add &
println!("id: {:?}", item.id);
}
fn main() {
let my_item = GroceryItem {
quantity: 3,
id: 99,
};
display_quantity(&my_item); // Add &
display_id(&my_item); // Add &
}
/*
Output
id:99
*/
✨ 更多可看 Rust檔案
enum Color {
Brown,
Red,
}
impl Color {
fn print(&self) {
match self {
Color::Brown => println!("brown"),
Color::Red => println!("red"),
}
}
}
Implement functionality on the box struct to create a new box.
struct Dimensions {
width: f64,
height: f64,
depth: f64,
}
impl Dimensions {
fn print(&self) {
println!("width: {:?}", self.width);
println!("height: {:?}", self.height);
println!("depth: {:?}", self.depth);
}
}
在結構體box實作功能,並輸出其特性(characteristics)
struct ShippingBox {
color: Color,
weight: f64,
dimensions: Dimensions,
}
impl ShippingBox {
fn new(weight: f64, color: Color, dimensions: Dimensions) -> Self {
Self {
weight,
color,
dimensions,
}
}
fn print(&self) {
self.color.print();
self.dimensions.print();
println!("weight: {:?}", self.weight);
}
}
Print out.
fn main() {
let small_dimensions = Dimensions {
width: 1.0,
height: 2.0,
depth: 3.0,
};
let small_box = ShippingBox::new(5.0, Color::Red, small_dimensions);
small_box.print();
}
/*
Red
width: 1.0
height: 2.0
depth: 3.0
weight: 5.0
*/
完整程式碼
enum Color {
Brown,
Red,
}
impl Color {
fn print(&self) {
match self {
Color::Brown => println!("brown"),
Color::Red => println!("red"),
}
}
}
struct Dimensions {
width: f64,
height: f64,
depth: f64,
}
impl Dimensions {
fn print(&self) {
println!("width: {:?}", self.width);
println!("height: {:?}", self.height);
println!("depth: {:?}", self.depth);
}
}
struct ShippingBox {
color: Color,
weight: f64,
dimensions: Dimensions,
}
impl ShippingBox {
fn new(weight: f64, color: Color, dimensions: Dimensions) -> Self {
Self {
weight,
color,
dimensions,
}
}
fn print(&self) {
self.color.print();
self.dimensions.print();
println!("weight: {:?}", self.weight);
}
}
fn main() {
let small_dimensions = Dimensions {
width: 1.0,
height: 2.0,
depth: 3.0,
};
let small_box = ShippingBox::new(5.0, Color::Red, small_dimensions);
small_box.print();
}